#!/bin/bash

NONE="\e[0m"
RED="\e[1;31m"
GREEN="\e[1;32m"
BLUE="\e[1;34m"


prepare_build()
{
	[ ! -d "$LOG_DIR" ] && mkdir -pv "$LOG_DIR" 
	[ ! -d "$LOCK_DIR" ] && mkdir -pv "$LOCK_DIR" 
	[ ! -f "$CACHE_FILE" ] && touch "$CACHE_FILE"
	[ ! -f "$ERROR_FILE" ] && touch "$ERROR_FILE"

	TOTAL_NUM=$(ls $SRC_DIR/*.src.rpm | wc -l)
	
}

LOG_OK()
{
	# remove from error cache file
	if [ -n $REBUILD ]; then
		grep -q "^$SRPM$" $ERROR_FILE
		if [ $? -eq 0 ]; then
		 	sed -i '/'"$SRPM"'/d' $ERROR_FILE
		fi
		FAILED_NUM=$((${FAILED_NUM} - 1))
	fi 

	# log in cache file
	grep -q "^$SRPM$" $CACHE_FILE
    	[ $? -ne 0 ] && echo "$SRPM" >> $CACHE_FILE
	echo -e "${GREEN}Package \"$NAME\" build OK! ${NONE}"
	SUCCESS_NUM=$((${SUCCESS_NUM} + 1))

	num=$(($num + 1))
}

LOG_ERROR()
{
	grep -q "^$SRPM$" $ERROR_FILE
	[ $? -ne 0 ] && echo "$SRPM" >> $ERROR_FILE
	echo -e "${RED}Package \"$NAME\" Failed, details see $LOG_FILE ${NONE}"
	FAILED_NUM=$((${FAILED_NUM} + 1))

	num=$(($num + 1))

	[ -n "$NOTIFY" ] && tail -n 100 $LOG_FILE | mail -s "build $NAME error" "$MAIL"
}

do_build()
{

	if [ -z "$SRC_LIST" ]; then
		SRPMS=$(find $SRC_DIR -name "*.src.rpm" -exec basename '{}' \; | tr '\n' ' ')
	else
		SRPMS=$(cat $SRC_LIST | tr '\n' ' ')
	fi 	

	num=0
	for SRPM in $SRPMS
	do
		if [ ! -f $SRC_DIR/$SRPM ]; then
		 	echo "No source package $SRPM found. Skip!"
			continue
		fi

		NAME=$(echo $SRPM | sed 's/-[0-9].*$//')
		LOG_FILE=$LOG_DIR/$NAME-${ARCH}-build.log
		LOCK_FILE=$LOCK_DIR/$NAME-${ARCH}.lock

		# it is bing building at this time
		if [ -f "$LOCK_FILE" ]; then
			echo -e "${BLUE}Package \"$NAME\" is building by others, skip.${NONE}"
			num=$(($num + 1))
		  	continue
		fi

		# let's build it
		touch $LOCK_FILE
		
		SUCCESS_NUM=$(wc -l "$CACHE_FILE" | awk '{printf $1'})
		FAILED_NUM=$(wc -l "$ERROR_FILE" | awk '{printf $1'})

		echo -e "\n${BLUE}############################################################${NONE}"
		echo -e "${BLUE}       total: $TOTAL_NUM${NONE}  ${GREEN}succeed: ${SUCCESS_NUM}${NONE}  ${RED}failed: ${FAILED_NUM} ${NONE}"	
		echo -e "${BLUE}############################################################${NONE}"

		# check status
		grep -q "^$SRPM$" $CACHE_FILE
		ret=$?
		if [ "$ret" -ne 0 ]; then
		        if [ -z "$REBUILD" ]; then
				grep -q "^$SRPM$" $ERROR_FILE
				if [ "$?" -eq 0 ]; then
					echo -e "${BLUE}Package \"$NAME\" alread build (${NONE}${RED}ERROR${NONE}${BLUE})${NONE}"
					num=$(($num + 1))
					rm -f $LOCK_FILE
					continue
				fi
			fi
		else
			echo -e "${BLUE}Package \"$NAME\" alread build (${NONE}${GREEN}OK${NONE}${BLUE})${NONE}"
			num=$(($num + 1))
			rm -f $LOCK_FILE
			continue
		fi

		
		
		
		SPEC_FILE=$(rpm -qlp $SRC_DIR/$SRPM 2>/dev/null| grep '.*\.spec$')
		SPEC=$SPEC_DIR/$SPEC_FILE
		echo -e "${GREEN}Package: $NAME ($(($num + 1)) / ${TOTAL_NUM})${NONE}"
		echo "Building package $SRPM" > $LOG_FILE
		echo -e "${GREEN}Installing source \"$SRPM\" ${NONE}"
		rpm -ivh $SRC_DIR/$SRPM &>> $LOG_FILE
		echo -e "${GREEN}Installing dependency for \"$SRPM\" ${NONE}"
		sudo yum-builddep --nogpgcheck -y $SRC_DIR/$SRPM &>> $LOG_FILE
		sed -i '/^%clean/,/^%.*$/{/ *rm.*\$RPM_BUILD_ROOT/s/\(rm\).*\(\$RPM_BUILD_ROOT\)/\1 -rf \2/}' $SPEC
		echo -e "${GREEN}Building \"$NAME\" ...${NONE}"
		yes | rpmbuild --clean -ba $SPEC &>> $LOG_FILE
		if [ "$?" -eq 0 ];then
			LOG_OK
		else
			LOG_ERROR
		fi
		
		# remove lock
		rm -f $LOCK_FILE
	done

	echo -e "${GREEN}All build mission done!${NONE}"
	[ -n "$NOTIFY" ] && echo "happy? :-)" | mail -s "All build mission done!" "$MAIL"
	
}

usage()
{
	echo 
	echo "################################################################################"
	echo "                            scripts for rpmbuild "
	echo "Usage: ./build-src.sh <-a arch> [-m] [-r] [-f <src list file>] [ -s <src rpm dir> ]"
	echo "################################################################################"
	echo 
	exit 
}

### start here

while [ $# -gt 0 ]
do
	case "$1" in
	-m)
	    NOTIFY="yes"
	    shift
	    ;;
	-r)
	    REBUILD="yes"
	    shift
	    ;;
	-a)
	    ARCH=$2
	    shift 2
	    ;;
	-f)
	    SRC_LIST=$2
	    shift 2
	    ;;
	-s) 
	    SRC_DIR=$2
	    shift 2
	    ;;
	*)
	    shift
	    ;;
	esac
done
	    
[ -z "$ARCH" ] && usage

trap 'echo "ctrl-C caught"; rm -fv $LOCK_FILE; kill -9 $$' 2

RPMBUILD_TOP=~/rpmbuild
SRC_DIR=${SRC_DIR:-"$RPMBUILD_TOP/SRPMS"}
SPEC_DIR=$RPMBUILD_TOP/SPECS
CACHE_FILE=build-${ARCH}-cache.pkg
ERROR_FILE=build-${ARCH}-error.pkg
LOG_DIR=./BUILD-LOG
LOCK_DIR=/tmp/rpmbuild-lock
TOTAL_NUM=""
SUCCESS_NUM=""
FAILED_NUM=""
MAIL="zxq_yx_007@163.com"

prepare_build
do_build
